package com.meiyuetao.myt.kuajing.service;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.lang3.StringUtils;
import org.jdom2.JDOMException;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.meiyuetao.myt.kuajing.entity.KjMesAskInfo;
import com.meiyuetao.myt.kuajing.entity.KjMessageTypeEnum;
import com.meiyuetao.myt.kuajing.entity.KjOrderBarCodeFb;
import com.meiyuetao.myt.kuajing.entity.KjOrderInfoFb;
import com.meiyuetao.myt.kuajing.entity.KjOrderStatusCodeEnum;
import com.meiyuetao.myt.kuajing.entity.KjPaymentInfoFb;
import com.meiyuetao.myt.kuajing.entity.KjPaymentStatusCodeEnum;
import com.meiyuetao.myt.kuajing.entity.KjSkuInfoFb;
import com.meiyuetao.myt.kuajing.entity.KjSkuStatusCodeEnum;
import com.meiyuetao.myt.md.entity.KjCommodityInfo;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.service.BoxOrderService;

@Service
public class YytReceiptInfoService {
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private BoxOrderService boxOrderService;
    @Autowired
    private KjMesAskInfoService kjMesAskInfoService;
    @Autowired
    private KjPaymentInfoService kjPaymentInfoService;
    @Autowired
    private KjSkuInfoFbService kjSkuInfoFbService;
    @Autowired
    private KjOrderInfoFbService kjOrderInfoFbService;
    @Autowired
    private KjOrderBarCodeFbService kjOrderBarCodeFbService;

    @Autowired
    private KjCommodityInfoService kjCommodityInfoService;

    public void parseXmlToObject(String xmlStr) {
        StringReader sr = new StringReader(xmlStr);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        NodeList nodes = doc.getElementsByTagName("MessageType");
        if (nodes.getLength() > 0) {
            String messageType = getFirstTextCnt(doc, "MessageType");
            if ("MES_ASK_INFO".equals(messageType)) {
                mesAskInfo(doc, xmlStr);
            } else if ("SKU_INFO_FB".equals(messageType)) {
                skuInfoFb(doc, xmlStr);
            } else if ("ORDER_INFO_FB".equals(messageType)) {
                orderInfoFb(doc, xmlStr);
            } else if ("PAYMENT_INFO_FB".equals(messageType)) {
                paymentInfoFb(doc, xmlStr);
            } else if ("ORDER_BAR_CODE_FB".equals(messageType)) {
                orderBarCodeFb(doc, xmlStr);
            }
        }

    }

    // 商品、订单、支付单、分运单号等的入库的回执
    private void mesAskInfo(Document doc, String xmlStr) {
        String messageId = getFirstTextCnt(doc, "MessageId");
        String messageTime = getFirstTextCnt(doc, "MessageTime");
        String senderId = getFirstTextCnt(doc, "SenderId");
        String senderAddress = getFirstTextCnt(doc, "SenderAddress");
        String receiverId = getFirstTextCnt(doc, "ReceiverId");
        String receiverAddress = getFirstTextCnt(doc, "ReceiverAddress");
        String platFormNo = getFirstTextCnt(doc, "PlatFormNo");
        String customCode = getFirstTextCnt(doc, "CustomCode");
        String seqNo = getFirstTextCnt(doc, "SeqNo");
        String note = getFirstTextCnt(doc, "Note");

        KjMesAskInfo kjMesAskInfo = new KjMesAskInfo();
        kjMesAskInfo.setMessageHeaderType(KjMessageTypeEnum.MES_ASK_INFO);
        kjMesAskInfo.setSenderId(senderId);
        kjMesAskInfo.setMessageId(messageId);
        kjMesAskInfo.setMessageTime(new DateTime(messageTime).toDate());
        kjMesAskInfo.setSenderAddress(senderAddress);
        kjMesAskInfo.setReceiverId(receiverId);
        kjMesAskInfo.setReceiverAddress(receiverAddress);
        kjMesAskInfo.setPlatFormNo(platFormNo);
        kjMesAskInfo.setCustomCode(customCode);
        kjMesAskInfo.setSeqNo(seqNo);
        kjMesAskInfo.setNote(note);
        kjMesAskInfo.setXmlStr(xmlStr);
        String messageBodyType = getFirstTextCnt(doc, "MESSAGE_TYPE");
        String workNo = getFirstTextCnt(doc, "WORK_NO");
        String createdNo = getFirstTextCnt(doc, "CREATED_NO");
        String opDate = getFirstTextCnt(doc, "OP_DATE");
        String success = getFirstTextCnt(doc, "SUCCESS");
        String memo = getFirstTextCnt(doc, "MEMO");
        String udf1 = getFirstTextCnt(doc, "UDF1");
        String udf2 = getFirstTextCnt(doc, "UDF2");
        String udf3 = getFirstTextCnt(doc, "UDF3");
        String udf4 = getFirstTextCnt(doc, "UDF4");
        String udf5 = getFirstTextCnt(doc, "UDF5");
        if (StringUtils.isNotBlank(messageBodyType)) {
            kjMesAskInfo.setMessageBodyType(KjMessageTypeEnum.valueOf(messageBodyType));
        }
        kjMesAskInfo.setWorkNo(workNo);
        kjMesAskInfo.setOpDate(new DateTime(opDate).toDate());
        kjMesAskInfo.setCreatedNo(createdNo);
        kjMesAskInfo.setSuccess(success);
        kjMesAskInfo.setMemo(memo);
        kjMesAskInfo.setUdf1(udf1);
        kjMesAskInfo.setUdf2(udf2);
        kjMesAskInfo.setUdf3(udf3);
        kjMesAskInfo.setUdf4(udf4);
        kjMesAskInfo.setUdf5(udf5);
        kjMesAskInfoService.save(kjMesAskInfo);
        // 商品入库
        if (KjMessageTypeEnum.SKU_INFO.equals(kjMesAskInfo.getMessageBodyType())) {
            String sku = kjMesAskInfo.getWorkNo();
            KjCommodityInfo kjCommodityInfo = kjCommodityInfoService.findByProperty("sku", sku);
            kjCommodityInfo.setKjMemo(kjCommodityInfo.addKjMemo(kjMesAskInfo.getOpDate(), success, memo));
            // kjCommodityInfo.setSkuStatusCode(KjSkuStatusCodeEnum.);
            kjCommodityInfoService.save(kjCommodityInfo);
        }
        if (KjMessageTypeEnum.ORDER_INFO.equals(kjMesAskInfo.getMessageBodyType())) {
            String orderSeq = kjMesAskInfo.getWorkNo();
            BoxOrder boxOrder = boxOrderService.findByOrderSeq(orderSeq);
            boxOrder.setKjMemo(boxOrder.addKjMemo(kjMesAskInfo.getOpDate(), success, memo));
            boxOrderService.save(boxOrder);
        }
        if (KjMessageTypeEnum.ORDER_INFO.equals(kjMesAskInfo.getMessageBodyType()) || KjMessageTypeEnum.ORDER_SET_TRANSPORT_NO.equals(kjMesAskInfo.getMessageBodyType())) {
            String orderSeq = kjMesAskInfo.getWorkNo();
            BoxOrder boxOrder = boxOrderService.findByOrderSeq(orderSeq);
            boxOrder.setKjMemo(boxOrder.addKjMemo(kjMesAskInfo.getOpDate(), success, memo));
            boxOrderService.save(boxOrder);
        }
        if (KjMessageTypeEnum.PAYMENT_INFO.equals(kjMesAskInfo.getMessageBodyType())) {
            String payVoucher = kjMesAskInfo.getWorkNo();
            BoxOrder boxOrder = boxOrderService.findByProperty("payVoucher", payVoucher);
            Assert.isTrue(boxOrder != null);
            boxOrder.setKjMemo(boxOrder.addKjMemo(kjMesAskInfo.getOpDate(), success, memo));
            boxOrderService.save(boxOrder);
        }
    }

    private void skuInfoFb(Document doc, String xmlStr) {
        KjSkuInfoFb kjSkuInfoFb = new KjSkuInfoFb();
        kjSkuInfoFb.setMessageHeaderType(KjMessageTypeEnum.SKU_INFO_FB);
        kjSkuInfoFb.setSenderId(getFirstTextCnt(doc, "SenderId"));
        kjSkuInfoFb.setMessageId(getFirstTextCnt(doc, "MessageId"));
        // TODO
        /*
         * kjSkuInfoFb.setMessageTime(DateUtils.parseDate(getFirstNodeValue(doc,
         * "MessageTime"), new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss")));
         */
        kjSkuInfoFb.setMessageTime(new DateTime(getFirstTextCnt(doc, "MessageTime")).toDate());
        kjSkuInfoFb.setSenderAddress(getFirstTextCnt(doc, "SenderAddress"));
        kjSkuInfoFb.setReceiverId(getFirstTextCnt(doc, "ReceiverId"));
        kjSkuInfoFb.setReceiverAddress(getFirstTextCnt(doc, "ReceiverAddress"));
        kjSkuInfoFb.setPlatFormNo(getFirstTextCnt(doc, "PlatFormNo"));
        kjSkuInfoFb.setCustomCode(getFirstTextCnt(doc, "CustomCode"));
        kjSkuInfoFb.setSeqNo(getFirstTextCnt(doc, "SeqNo"));
        kjSkuInfoFb.setNote(getFirstTextCnt(doc, "Note"));
        kjSkuInfoFb.setXmlStr(xmlStr);
        kjSkuInfoFb.setSku(getFirstTextCnt(doc, "SKU"));
        kjSkuInfoFb.setSkuStatusCode(KjSkuStatusCodeEnum.valueOf("KJS_" + getFirstTextCnt(doc, "STATUS_CODE")));
        kjSkuInfoFb.setOpDate(new DateTime(getFirstTextCnt(doc, "OP_DATE")).toDate());
        kjSkuInfoFb.setMemo(getFirstTextCnt(doc, "MEMO"));
        kjSkuInfoFbService.save(kjSkuInfoFb);
        KjCommodityInfo kjCommodityInfo = kjCommodityInfoService.findByProperty("sku", kjSkuInfoFb.getSku());
        kjCommodityInfo.setSkuStatusCode(kjSkuInfoFb.getSkuStatusCode());
        kjCommodityInfoService.save(kjCommodityInfo);

    }

    private void orderInfoFb(Document doc, String xmlStr) {
        KjOrderInfoFb kjOrderInfoFb = new KjOrderInfoFb();
        kjOrderInfoFb.setMessageHeaderType(KjMessageTypeEnum.ORDER_INFO_FB);
        kjOrderInfoFb.setSenderId(getFirstTextCnt(doc, "SenderId"));
        kjOrderInfoFb.setMessageId(getFirstTextCnt(doc, "MessageId"));
        kjOrderInfoFb.setMessageTime(new DateTime(getFirstTextCnt(doc, "MessageTime")).toDate());
        kjOrderInfoFb.setSenderAddress(getFirstTextCnt(doc, "SenderAddress"));
        kjOrderInfoFb.setReceiverId(getFirstTextCnt(doc, "ReceiverId"));
        kjOrderInfoFb.setReceiverAddress(getFirstTextCnt(doc, "ReceiverAddress"));
        kjOrderInfoFb.setPlatFormNo(getFirstTextCnt(doc, "PlatFormNo"));
        kjOrderInfoFb.setCustomCode(getFirstTextCnt(doc, "CustomCode"));
        kjOrderInfoFb.setSeqNo(getFirstTextCnt(doc, "SeqNo"));
        kjOrderInfoFb.setNote(getFirstTextCnt(doc, "Note"));
        kjOrderInfoFb.setXmlStr(xmlStr);
        kjOrderInfoFb.setOrderNo(getFirstTextCnt(doc, "ORDER_NO"));
        kjOrderInfoFb.setOriginalOrderNo(getFirstTextCnt(doc, "ORIGINAL_ORDER_NO"));
        kjOrderInfoFb.setOrderStatusCode(KjOrderStatusCodeEnum.valueOf("KJO_" + getFirstTextCnt(doc, "STATUS_CODE")));
        kjOrderInfoFb.setOpDate(new DateTime(getFirstTextCnt(doc, "OP_DATE")).toDate());
        kjOrderInfoFb.setMemo(getFirstTextCnt(doc, "MEMO"));
        kjOrderInfoFbService.save(kjOrderInfoFb);

        BoxOrder order = boxOrderService.findByProperty("orderSeq", kjOrderInfoFb.getOrderNo());
        order.setKjOrderStatusCode(kjOrderInfoFb.getOrderStatusCode());
        order.setKjMemo(kjOrderInfoFb.getMemo());
        boxOrderService.save(order);

    }

    private void paymentInfoFb(Document doc, String xmlStr) {
        KjPaymentInfoFb kjPaymentInfb = new KjPaymentInfoFb();
        kjPaymentInfb.setMessageHeaderType(KjMessageTypeEnum.ORDER_INFO_FB);
        kjPaymentInfb.setSenderId(getFirstTextCnt(doc, "SenderId"));
        kjPaymentInfb.setMessageId(getFirstTextCnt(doc, "MessageId"));
        kjPaymentInfb.setMessageTime(new DateTime(getFirstTextCnt(doc, "MessageTime")).toDate());
        kjPaymentInfb.setSenderAddress(getFirstTextCnt(doc, "SenderAddress"));
        kjPaymentInfb.setReceiverId(getFirstTextCnt(doc, "ReceiverId"));
        kjPaymentInfb.setReceiverAddress(getFirstTextCnt(doc, "ReceiverAddress"));
        kjPaymentInfb.setPlatFormNo(getFirstTextCnt(doc, "PlatFormNo"));
        kjPaymentInfb.setCustomCode(getFirstTextCnt(doc, "CustomCode"));
        kjPaymentInfb.setSeqNo(getFirstTextCnt(doc, "SeqNo"));
        kjPaymentInfb.setNote(getFirstTextCnt(doc, "Note"));
        kjPaymentInfb.setXmlStr(xmlStr);
        kjPaymentInfb.setPaymentNo(getFirstTextCnt(doc, "PAYMENT_NO"));
        kjPaymentInfb.setPaymentStatusCode(KjPaymentStatusCodeEnum.valueOf("KJP_" + getFirstTextCnt(doc, "STATUS_CODE")));
        kjPaymentInfb.setOpDate(new DateTime(getFirstTextCnt(doc, "OP_DATE")).toDate());
        kjPaymentInfb.setMemo(getFirstTextCnt(doc, "MEMO"));

        BoxOrder order = boxOrderService.findByProperty("orderSeq", kjPaymentInfb.getPaymentNo());
        order.setKjPaymentStatusCode(kjPaymentInfb.getPaymentStatusCode());
        order.setKjPaymentMemo(kjPaymentInfb.getMemo());
        boxOrderService.save(order);
    }

    private String getFirstTextCnt(Document doc, String name) {
        NodeList nodes = doc.getElementsByTagName(name);
        if (nodes != null && nodes.getLength() > 0) {
            // String nodeValue = nodes.item(0).getNodeValue();
            String nodeValue = nodes.item(0).getTextContent();
            return nodeValue;
        }
        return null;
    }

    // 订单条形码反馈
    private void orderBarCodeFb(Document doc, String xmlStr) {
        KjOrderBarCodeFb kjOrderBarCodeFb = new KjOrderBarCodeFb();
        kjOrderBarCodeFb.setMessageHeaderType(KjMessageTypeEnum.ORDER_BAR_CODE_FB);
        kjOrderBarCodeFb.setSenderId(getFirstTextCnt(doc, "SenderId"));
        kjOrderBarCodeFb.setMessageId(getFirstTextCnt(doc, "MessageId"));
        kjOrderBarCodeFb.setMessageTime(new DateTime(getFirstTextCnt(doc, "MessageTime")).toDate());
        kjOrderBarCodeFb.setSenderAddress(getFirstTextCnt(doc, "SenderAddress"));
        kjOrderBarCodeFb.setReceiverId(getFirstTextCnt(doc, "ReceiverId"));
        kjOrderBarCodeFb.setReceiverAddress(getFirstTextCnt(doc, "ReceiverAddress"));
        kjOrderBarCodeFb.setPlatFormNo(getFirstTextCnt(doc, "PlatFormNo"));
        kjOrderBarCodeFb.setCustomCode(getFirstTextCnt(doc, "CustomCode"));
        kjOrderBarCodeFb.setSeqNo(getFirstTextCnt(doc, "SeqNo"));
        kjOrderBarCodeFb.setNote(getFirstTextCnt(doc, "Note"));
        kjOrderBarCodeFb.setXmlStr(xmlStr);
        kjOrderBarCodeFb.setOrderNo(getFirstTextCnt(doc, "ORDER_NO"));
        kjOrderBarCodeFb.setOriginalOrderNo(getFirstTextCnt(doc, "ORIGINAL_ORDER_NO"));
        kjOrderBarCodeFb.setBarCode(getFirstTextCnt(doc, "BAR_CODE"));

        kjOrderBarCodeFbService.save(kjOrderBarCodeFb);

        BoxOrder order = boxOrderService.findByProperty("orderSeq", kjOrderBarCodeFb.getOrderNo());
        order.setKjBarCode(kjOrderBarCodeFb.getBarCode());
        boxOrderService.save(order);
    }

    public static void main(String[] args) throws JDOMException, IOException {
        String xml = " <DTC_Message>  <MessageHead>    <MessageType>SKU_INFO_FB</MessageType>    <MessageId>5abd525c-e75f-41b0-b873-33e3072e2512</MessageId>    <MessageTime>2015-02-04T18:01:53</MessageTime>    <SenderId>CQITC</SenderId>    <SenderAddress />    <ReceiverId>MYTC102015</ReceiverId>    <ReceiverAddress />    <PlatFormNo />    <CustomCode />    <SeqNo>bce92b2a-6160-42f3-948a-cb9de244e6cb</SeqNo>    <Note />  </MessageHead>  <MessageBody>    <DTCFlow>      <SKU_INFO_FB>        <SKU>57352866</SKU>        <STATUS_CODE>30</STATUS_CODE>        <OP_DATE>2015-02-04T18:01:49</OP_DATE>        <MEMO />      </SKU_INFO_FB>    </DTCFlow>  </MessageBody></DTC_Message>";

        xml = xml.replace(" ", "");
        xml = "<?xml version='1.0' encoding='utf-8'?>" + xml;

        StringReader sr = new StringReader(xml);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        NodeList nodes = doc.getElementsByTagName("MessageType");
        System.out.println(nodes.item(0).getTextContent());

    }
}
